package com.aruba.flowapplyapplication.viewmodel

import android.view.View
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.aruba.flowapplyapplication.database.MyDatabase
import com.aruba.flowapplyapplication.database.dao.UserInfoDao
import com.aruba.flowapplyapplication.database.entity.UserInfo
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.launch
import androidx.databinding.ObservableField


/**
 * Created by aruba on 2021/9/20.
 */
class UserInfoViewModel : ViewModel() {
    val id = MutableLiveData<String>()
    val name = MutableLiveData<String>()
    val age = MutableLiveData<String>()

    private val userInfoDao: UserInfoDao by lazy {
        MyDatabase.getInstance().getUserDao()
    }

    fun insert(v: View) {
        if (id.value == null || name.value == null || age.value == null) {
            return
        }

        val userInfo = UserInfo(id.value!!.toInt(), name.value!!, age.value!!.toInt())
        viewModelScope.launch(Dispatchers.IO) {
            userInfoDao.insert(userInfo)
        }
    }

    fun getUserInfo(): Flow<List<UserInfo>> {
        return userInfoDao
            .getUserInfoList()
            .flowOn(Dispatchers.IO)
    }

}